package com.javakc.cms.book.controller;

import com.javakc.cms.book.entity.Book;
import com.javakc.cms.book.service.BookService;

import com.javakc.cms.book.vo.BookQuery;
import com.javakc.commonutils.api.APICODE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @ClassName Controller
 * @Description 书籍信息管理 - 表现类
 * @Author xujie
 * @Date 2021/11/3
 * @Version 1.0.0
 **/
@Api(tags = "书籍信息管理")
@RestController
@RequestMapping("/cms/book")
@CrossOrigin
public class BookController {
    @Autowired
    private BookService bookService;

    @ApiOperation(value = "查询所有书籍")
    @GetMapping
    public APICODE findBook() {
        List<Book> list = bookService.findBook();
        return APICODE.OK().data("items",list);
    }

    @ApiOperation("带分页的条件查询")
    @PostMapping("{pageNo}/{pageSize}")
    public APICODE findPage(
            @ApiParam(name="pageNo",value = "当前页码",required = true) @PathVariable("pageNo") int pageNo,
            @ApiParam(name="pageSize",value = "每页显示的最大条数",required = true) @PathVariable("pageSize") int pageSize,
            @ApiParam(name="bookQuery",value = "查询条件封装对象",required = false) @RequestBody(required = false) BookQuery bookQuery){
        Page<Book> page = bookService.findPage(pageNo, pageSize, bookQuery);
        List<Book> list = page.getContent();
        long totalElements = page.getTotalElements();
        return APICODE.OK().data("items",list).data("total",totalElements);
    }

    @ApiOperation(value = "新增书籍")
    @PostMapping("saveBook")
    public APICODE saveBook(@RequestBody Book book){
        bookService.saveOrUpdate(book);
        return APICODE.OK().data("book",book);
    }

    @ApiOperation(value = "修改书籍")
    @PutMapping("updateBook")
    public APICODE updateBook(@RequestBody Book book){
        bookService.saveOrUpdate(book);
        return APICODE.OK().data("book",book);
    }

    @ApiOperation(value = "根据ID获取书籍")
    @GetMapping("{bookId}")
    public APICODE view(@PathVariable("bookId") int bookId){
        Book book = bookService.getById(bookId);
        return APICODE.OK().data("book",book);
    }

    @ApiOperation(value = "根据ID删除书籍")
    @DeleteMapping("{id}")
    public APICODE deleteBook(@PathVariable int id){
        bookService.removeById(id);
        return APICODE.OK();
    }
}
